package com.conan.controller;


import com.conan.pojo.Result;
import com.conan.pojo.User;
import com.conan.service.UserService;
import com.conan.utils.JwtUtil;
import com.conan.utils.Md5Util;
import com.conan.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.apache.el.parser.Token;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate redisTemplate;
    //注册接口
    @PostMapping("/register")
    //@Pattern注解，^和$之间是方法体,\是转义字符,\s表示非空.5,16表示5-16
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username,
                           @Pattern(regexp = "^\\S{5,16}$")String password) {
//        if(username !=null && username.length()>5 && username.length()<16
//                && password !=null && password.length()>8 && password.length()<16) {
        if(userService.findByUsername(username) != null) {
            return Result.error("用户名已经占用");
        }else{
            userService.register(username, password);
            return Result.success();
        }
//        }else{
//            return Result.error("用户名或密码格式不正确");
//        }
    }

    //登录接口
    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username,
                                @Pattern(regexp = "^\\S{5,16}$") String password){
            User user = userService.findByUsername(username);
            if(user == null){
                return Result.error("用户名或密码错误");
            }else{
                if(Md5Util.getMD5String(password).equals(user.getPassword())){
                    Map<String, Object> data = new HashMap<>();
                    data.put("id",user.getId());
                    data.put("username",user.getUsername());
                    String token = JwtUtil.genToken(data);
                    //登陆成功后，把令牌相应到浏览器之前，将其存储到Redis
                    //token即作为键又作为值存到redis
                    //将来把redis携带的token作为值，用redis获取。
                    ValueOperations<String,String> operations = redisTemplate.opsForValue();
                    //设置redis中token的过期时间，与token生成的过期时间相同
                    //如果redis不过期，redis的数据会越来越多
                    operations.set(token,token,1, TimeUnit.HOURS);
                    return Result.success(token);
                }else{
                    return Result.error("用户名或密码错误");
                }
            }
    }
    //查询用户信息
    @GetMapping("/userInfo")
    public Result<User> findByUsername(/*@RequestHeader(name = "Authorization") String tokenUser username*/){
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUsername(username);
        return Result.success(user);
    }

    //更新用户信息
    @PutMapping("/update")
    public Result updateUser(@RequestBody @Validated User user){
        userService.updateUser(user);
        return Result.success();
    }

    //更新用户头像
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarURL){
        userService.updateAvatar(avatarURL);
        return Result.success();
    }

    //更新用户密码
    @PatchMapping("/updatePWD")
    public Result updatePWD(@RequestBody Map<String,String> params,@RequestHeader("Authorization") String token){
        String oldPwd = params.get("oldPwd");
        String newPwd = params.get("newPwd");
        String rePwd = params.get("rePwd");

        if(!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)){
            return Result.error("缺少必要参数");
        }

        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUsername(username);
        if(!user.getPassword().equals(Md5Util.getMD5String(oldPwd))){
            return Result.error("原密码不正确");
        }
        if(!newPwd.equals(rePwd)){
            return Result.error("输入的两次密码不一致");
        }
        userService.updatePassword(newPwd);

        //更新密码后，删除redis中的旧token，
        //根据浏览器携带过来的token来删除redis中的旧的端口
        //获取浏览器携带过来的token，在方法参数上声明。
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        operations.getOperations().delete(token);
        return Result.success();
    }

}
